'use strict';

angular.module('xianwan').factory('MessageTemplate', function (Xss) {

    let getValue = function (keyword, data) {
        let value = '';
        if (data) {
            let result = data.filter(function (item) {
                return item.key == keyword;
            });
            if (result.length > 0) {
                value = result[0];
            }
        }
        return value;
    }

    let getKeyword = function (str) {
        return str.substring(2, str.length - 7)
    }

    let replaceKeyword = function (content, keyword, data, packageToSpan) {
        if (!data || !data.value) {
            return content.replace(keyword, '');
        }
        data.value = Xss.filter(data.value);
        if (packageToSpan) {
            let spanHtml = '<span style=font-size:' + data.font_size + 'px;color:' + data.color + ';font-weight:' + data.text_style + '>' + data.value + '</span>';
            return content.replace(keyword, spanHtml);
        }
        return content.replace(keyword, data.value);
    }
    
    let replaceTemplateParams = function (item, message, packageToSpan) {
        if (item) {
            let keywords = item.match(/\{{[\s\S]*?\.DATA\}}/g);
            if (keywords) {
                keywords.forEach(function (k) {
                    let keyword = getKeyword(k);
                    let value = getValue(keyword, message.body.data);
                    item = replaceKeyword(item, k, value, packageToSpan);
                })
            }
        }
        return item;
    }

    return {

        replaceTemplateParams: function (message) {
            if (message.body.replaceSuccess) {
                return;
            }
            console.log(message.body.contents)
            if (message.body.contents) {
                message.body.contents.forEach(function (content) {
                    content.forEach(function (item) {
                        item.content = Xss.filter(item.content);
                        item.content = replaceTemplateParams(item.content, message, true);
                    })
                })
            }
            if (message.body.actions) {
                message.body.actions.forEach(function (item) {
                    item.name = replaceTemplateParams(item.name, message, false);
                    item.value = replaceTemplateParams(item.value, message, false);
                })
            }
            message.body.replaceSuccess = true;
        }

    }

});
